package com.jpress.control;

import java.util.Calendar;
import java.util.List;

import com.jpress.dao.DAOAdmin;
import com.jpress.dao.DAOBlog;
import com.jpress.model.Blog;

public class BlogControl {
	DAOBlog daoBlog = new DAOBlog();
	DAOAdmin daoAdmin = new DAOAdmin();

	public int getBlogQtde() {
		return (int) this.daoBlog.findAll().size();
	}

	public List<Blog> getUltimosBlogs() {
		return this.daoBlog.findAllWithMax(10);
	}

/*	public boolean cadastrarBlog(Blog novoBlog) {
		try {
			this.daoBlog.begin();
			this.daoBlog.persist((Blog) novoBlog);
			this.daoBlog.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally{
			this.daoBlog.close();
		}
	}
*/	
	public boolean cadastrarBlog(Blog novoBlog, int idAdmin){
		try {
			novoBlog.setDataCriacao(Calendar.getInstance());
			novoBlog.setDono(daoAdmin.findById(idAdmin));
			this.daoBlog.begin();
			this.daoBlog.persist((Blog) novoBlog);
			this.daoBlog.commit();
			return true;
		} catch (Exception e) {
			return false;
		}finally{
			this.daoBlog.close();
		}
	}

	public List<Blog> meusBlogs(int id) {
		String query = "SELECT b FROM Blog b WHERE b.dono.id = '" + String.valueOf(id) + "' ORDER BY b.dataCriacao DESC";
		return this.daoBlog.findAllWithMaxWithQuery(query, 5);
	}

	public Blog getBlogById(int id) {
		return this.daoBlog.findById(id);
	}

	public boolean excluirBlog(Blog blog) {
		try {
			this.daoBlog.begin();
			this.daoBlog.remove(blog);
			this.daoBlog.commit();
			return true;
		} catch (Exception e) {
			return false;
		} finally{
			this.daoBlog.close();
		}
	}

	public boolean atualizarBlog(Blog blog) {
		try {
			this.daoBlog.begin();
			this.daoBlog.merge(blog);
			this.daoBlog.commit();
			return true;
		} catch (Exception e) {
			return false;
		}finally{
			this.daoBlog.close();
		}
	}

	public boolean verificarBlogCadastrado(String nomeBlog) {
		if(this.daoBlog.findByNome(nomeBlog) != null){
			return false;
		}
		return true;

	}

}
